package com.base.sys.controller;

import com.base.redis.RedisUtil;
import com.base.sys.entity.SysUser;
import com.base.sys.service.ISysDictService;
import com.base.sys.service.ISysUserService;
import com.base.util.CodeGenerator;
import com.base.util.IDUtil;
import com.base.util.Result;
import com.base.util.Seaweedfs;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import net.anumbrella.seaweedfs.core.FileSource;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("index")
public class IndexController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private Seaweedfs seaweedfs;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDictService sysDictService;

    @RequestMapping(value = "/captcha-image")
    public ModelAndView getKaptchaImage(HttpServletRequest request,
                                        HttpServletResponse response) throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control",
                "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        String capText = defaultKaptcha.createText();
        System.out.println("capText: " + capText);
        try {
            String uuid = UUID.randomUUID().toString();
            redisUtil.set(uuid + "_code", capText);
            Cookie cookie = new Cookie("captchaCode", uuid + "_code");
            cookie.setMaxAge(7200);
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
        BufferedImage bi = defaultKaptcha.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }

    @RequestMapping("/upload-file")
    @ResponseBody
    public Result uploadFile(MultipartFile file)throws Exception{
        FileSource fileSource = seaweedfs.startup();
        String fileId = seaweedfs.uploadFile(fileSource, file.getName(), file);
        SysUser sysUser=(SysUser) SecurityUtils.getSubject().getPrincipal();
        String id = sysUser.getId();
        //为了防止version已被更新,这里重新获取用户对象
        SysUser dataSysUser = sysUserService.getById(id);
        String avatar = dataSysUser.getAvatar();
        if(!StringUtils.isEmpty(avatar)){
            //删除原头像
            seaweedfs.deleteFile(fileSource,avatar);
        }
        dataSysUser.setAvatar(fileId);
        sysUserService.updateById(dataSysUser);
        String url="http://"+seaweedfs.getHost()+":"+seaweedfs.getPort()+"/"+fileId;
        return Result.successResult(url);
    }



    @RequestMapping("/get-tables/{tableName}")
    @ResponseBody
    public Result getTables(@PathVariable String tableName){
       return sysDictService.getTables(tableName);
    }

    @RequestMapping("/generator")
    @ResponseBody
    public Result generator(@RequestBody Map<String,Object> map){
        String tableName = map.get("tableName").toString();
        String author = map.get("author").toString();
        String moduleName = map.get("moduleName").toString();
        CodeGenerator.generator(tableName,author,moduleName);
        return Result.successResult();
    }




}